# coding=utf-8

import requests
import json
from utils.exceptions import CustomError


class WeChat(object):

    @staticmethod
    def getPreAuthCode(component_appid, component_access_token):
        """
        第三方平台  获得预授权码
        结果{"pre_auth_code": "Cx_Dk6qiBE0Dmx4EmlT3oRfArPvwSQ-oa3NL_fwHM7VI08r52wazoZX2Rhpz1dEw", "expires_in": 600}
        """

        url = 'https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=' + component_access_token
        param = {
            'component_appid': component_appid,
        }
        result = requests.post(url, data=json.dumps(param))
        result = result.json()
        if 'errcode' in result and result['errcode']:
            raise CustomError(u'微信请求失败' + str(result['errcode']) + ' :' + result['errmsg'])
        return result

    @staticmethod
    def getComponentAccessToken(component_appid, component_appsecret, component_verify_ticket):
        """第三方平台  获得access_token"""

        url = 'https://api.weixin.qq.com/cgi-bin/component/api_component_token'
        param = {
            'component_appid': component_appid,
            'component_appsecret': component_appsecret,
            'component_verify_ticket': component_verify_ticket
        }
        result = requests.post(url, data=json.dumps(param))
        result = result.json()
        if 'errcode' in result and result['errcode']:
            raise CustomError(u'微信请求失败'+ str(result['errcode']) + ' :' + result['errmsg'])
        return result

    @staticmethod
    def getAuthorizationInfo(component_appid, authorization_code, component_access_token):
        """第三方平台  获得授权信息"""

        url = 'https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=' + component_access_token
        param = {
            'component_appid': component_appid,
            'authorization_code': authorization_code,
        }
        result = requests.post(url, data=json.dumps(param))
        result = result.json()
        if 'errcode' in result and result['errcode']:
            raise CustomError(u'微信请求失败'+ str(result['errcode']) + ' :' + result['errmsg'])
        return result

    @staticmethod
    def getAuthorizerInfo(component_appid, authorizer_appid, component_access_token):
        """第三方平台 获得授权方信息"""

        url = 'https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token=' + component_access_token
        param = {
            'component_appid': component_appid,
            'authorizer_appid': authorizer_appid,
        }
        result = requests.post(url, data=json.dumps(param))
        result = result.json()
        if 'errcode' in result and result['errcode']:
            raise CustomError(u'微信请求失败'+ str(result['errcode']) + ' :' + result['errmsg'])
        return result

    @staticmethod
    def getAuthorizerAccessToken(component_appid, authorizer_appid, authorizer_refresh_token, component_access_token):
        """第三方平台 获得授权方 access_token"""

        url = 'https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token=' + component_access_token
        param = {
            'component_appid': component_appid,
            'authorizer_appid': authorizer_appid,
            'authorizer_refresh_token': authorizer_refresh_token
        }
        result = requests.post(url, data=json.dumps(param))
        result = result.json()
        if 'errcode' in result and result['errcode']:
            raise CustomError(u'微信请求失败'+ str(result['errcode']) + ' :' + result['errmsg'])
        return result

    @staticmethod
    def getCodeTemplateList(component_access_token):
        '''获取代码模版列表'''

        url = 'https://api.weixin.qq.com/wxa/gettemplatelist?access_token=' + component_access_token
        result = requests.get(url)
        result = result.json()
        if 'errcode' in result and result['errcode']:
            raise CustomError(u'微信请求失败'+ str(result['errcode']) + ' :' + result['errmsg'])
        return result['template_list']

    @staticmethod
    def commitCode(access_token, template_id, user_version, user_desc):
        '''小程序提交代码'''
        url = 'https://api.weixin.qq.com/wxa/commit?access_token=' + access_token

        param = {
            'template_id': template_id,
            'ext_json': "{\"extEnable\": false,\"extAppid\": \"\"}",
            'user_version': user_version,
            'user_desc': 'test'
        }

        result = requests.post(url, data=json.dumps(param))
        result = result.json()
        if 'errcode' in result and result['errcode']:
            raise CustomError(u'微信请求失败'+ str(result['errcode']) + ' :' + result['errmsg'])
        return result

    @staticmethod
    def submitAuditCode(access_token):
        '''将上传的代码提交审核'''

        url = 'https://api.weixin.qq.com/wxa/submit_audit?access_token=' + access_token

        result = requests.post(url)
        result = result.json()
        if 'errcode' in result and result['errcode']:
            raise CustomError(u'微信请求失败' + str(result['errcode']) + ' :' + result['errmsg'])
        return result

    @staticmethod
    def getLastSubmitAuditCodeStatus(access_token):
        '''查询最新一次提交审核代码的审核状态'''

        url = 'https://api.weixin.qq.com/wxa/get_latest_auditstatus?access_token=' + access_token
        result = requests.get(url)
        result = result.json()
        if 'errcode' in result and result['errcode']:
            raise CustomError(u'微信请求失败' + str(result['errcode']) + ' :' + result['errmsg'])
        return result

    @staticmethod
    def modify_domain(access_token, action, requestdomain, wsrequestdomain, uploaddomain, downloaddomain):
        '''设置小程序服务器域名'''
        url = 'https://api.weixin.qq.com/wxa/modify_domain?access_token=' + access_token

        param = {
            "action": action,
            "requestdomain": requestdomain,
            "wsrequestdomain": wsrequestdomain,
            "uploaddomain": uploaddomain,
            "downloaddomain": downloaddomain
        }
        result = requests.post(url, data=json.dumps(param))
        result = result.json()
        if 'errcode' in result and result['errcode']:
            raise CustomError(u'微信请求失败' + str(result['errcode']) + ' :' + result['errmsg'])
        return result

    @staticmethod
    def code2Session(appid, secret, code):
        '''登录凭证校验'''
        url = 'https://api.weixin.qq.com/sns/jscode2session?appid='+ appid + '&secret=' + secret + '&js_code=' + code + '&grant_type=authorization_code'
        result = requests.get(url)
        result = result.json()
        if 'errcode' in result and result['errcode']:
            raise CustomError(u'微信请求失败' + str(result['errcode']) + ':' + result['errmsg'])
        return result

    @staticmethod
    def addPlugin(access_token):
        '''小程序插件管理'''
        url = 'https://api.weixin.qq.com/wxa/plugin?access_token=' + access_token

        param = {
            'action': 'apply',
            'plugin_appid': 'wxfa43a4a7041a84de'
        }

        result = requests.post(url, data=json.dumps(param))
        result = result.json()
        if 'errcode' in result and result['errcode'] and str(result['errcode']) != '89237':
            raise CustomError(u'微信请求失败' + str(result['errcode']) + ':' + result['errmsg'])
        return result

    @staticmethod
    def getTemplateList(access_token):
        '''获取当前帐号下的个人模板列表'''
        url = 'https://api.weixin.qq.com/wxaapi/newtmpl/gettemplate?access_token=' + access_token
        result = requests.get(url)
        result = result.json()
        if 'errcode' in result and result['errcode']:
            raise CustomError(u'微信请求失败' + str(result['errcode']) + ':' + result['errmsg'])
        return result['data']

    @staticmethod
    def sendSubscribeMessage(access_token, openid, template_id, page, data):
        '''发送订阅消息'''
        url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' + access_token

        param = {
            'touser': openid,
            'template_id': template_id,
            'page': page,
            'data': data
        }
        result = requests.post(url, data=json.dumps(param))
        #print('-------------------------')
        #result = result.json()
        #print(result)

        #result = requests.post(url, data=json.dumps(param))
        #result = result.json()
        #if 'errcode' in result and result['errcode'] and str(result['errcode']) != '89237':
        #    raise CustomError(u'微信请求失败' + str(result['errcode']) + ':' + result['errmsg'])
        #return result

    @staticmethod
    def releaseCode(access_token):
        '''已审核代码发布'''

        url = 'https://api.weixin.qq.com/wxa/release?access_token=' + access_token

        result = requests.post(url, data=json.dumps({}))
        result = result.json()
        if 'errcode' in result and result['errcode']:
            raise CustomError(u'微信请求失败' + str(result['errcode']) + ' :' + result['errmsg'])
        return result
